/// Creator:      gaoruishan
/// CreatDate:    2025-06-06
/// Description:  手术相关
Class Nur.MNISV3.Service.Operation Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// 手术查询列表
/// w ##class(Nur.MNISV3.Service.Operation).GetOpsDataV4("","2023-06-08","2025-06-10","{""single"":"""",""multiple"":""1""}","3","8","2")
ClassMethod GetOpsDataV4(episodeId = "", fromDate = "", toDate = "", extras = "", wardId = "", locId = "", hospitalId = "")
{
    n (episodeId,fromDate,toDate,extras,wardId,locId,hospitalId)
    s $zt="errGetOpsDataV4"
    s ^GRS("GetOpsDataV4")=$lb(episodeId,fromDate,toDate,extras,wardId,locId,hospitalId)
    
    /// 兼容老板本-获取PDA手术列表
    //q ##class(Nur.MNISV3.Service.Operation).GetOperationList(wardId,fromDate,"00:00",toDate,"23:59")

    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s patInfoList=##class(%ListOfDataTypes).%New()
    k tempPats
    i episodeId'="" { //单患者--TODO 暂时不做
       // ":"2025-06-06","groupId":"23","extras":"{\"single\":\"\",\"multiple\":\"1\"}","wardId":"3","secret":"aU1lZGljYWwtTnVyc2UtUERBNC4wT3BlcmF0aW9uRnJhZ21lbnRkYzMwYThhMzE5MjcyNWFkXkRU\nNTBIMTc0OTE5MjgxNTUwOA==\n","logonInfo":"{\"hospitalId\":\"2\",\"groupId\":\"23\",\"wardId\":\"3\",\"userId\":\"20665\",\"locId\":\"8\"}","deviceId":"dc30a8a3192725ad^DT50H^192.168.1.107,
       // ","userId":"20665","fromDate":"2025-06-04","fragment":"OperationFragment","hospitalId":"2","locId":"8",
    }else {
        ;;;按单个病人查，按登记号不过滤日期太卡，改为按病区查
        //d ##class(%ResultSet).RunQuery("CIS.AN.BL.OperScheduleList","FindOperScheduleList","2023-08-29","2023-09-06","93","","","","","","","","","N","N")
        //1 startDate ,2 endDate ,3 userDeptID,4 opsId,5 appDeptID,6 patWardID,7 operStatusID,8 operRoomID,9 regNo,10 medcareNo,11 byAppDate,12 isDaySurgery,13 isOutOper,14 EMStatusID,15 HospDr 
        s patListObj=##class(%ResultSet).%New("CIS.AN.BL.OperScheduleList:FindOperScheduleList")
        d patListObj.Execute(fromDate,toDate,locId,"","",locId,"","","","","","N","N","",hospitalId)
        //d patListObj.Execute("2023-08-29","2023-09-02","93","","","","","","","","","N","N","")
        while(patListObj.Next()){
            
            s patinfo=##class(%ArrayOfDataTypes).%New()
            s opsData=##class(%ListOfDataTypes).%New()
            s opsObj=##class(%ArrayOfDataTypes).%New()
            f len=1:1:patListObj.GetColumnCount()
            {
                 s ColumnName=patListObj.GetColumnName(len) 
                 s Value=patListObj.GetDataByName(ColumnName)
                 i ColumnName="PatBedCode" d patinfo.SetAt(Value,"bedCode")
                 i ColumnName="EpisodeID" d patinfo.SetAt(Value,"episodeID")
                 i ColumnName="MedcareNo" d patinfo.SetAt(Value,"medicareNo")
                 i ColumnName="PatName" d patinfo.SetAt(Value,"name")
                 i ColumnName="RegNo" d patinfo.SetAt(Value,"regNo")
                 i ColumnName="PatGender" d patinfo.SetAt(Value,"sex")
                 s b1=(ColumnName="AnaMethodDesc")||(ColumnName="AsstDesc")||(ColumnName="DaySurgery")||(ColumnName="OeoreID")||(ColumnName="OperClassDesc")
                 s b2=(ColumnName="OperDate")||(ColumnName="OperDesc")||(ColumnName="OperSeq")||(ColumnName="PlanSeq")||(ColumnName="RoomDesc")
                 s b3=(ColumnName="SourceTypeDesc")||(ColumnName="StatusColor")||(ColumnName="StatusDesc")||(ColumnName="SurgeonDesc")||(ColumnName="RoomDesc")
                 
                 i b1||b2||b3 {
                     d opsObj.SetAt(Value,ColumnName)
                 }
            }
            s episodeId=patListObj.GetDataByName("EpisodeID")
            i $g(tempPats(episodeId))'="" { //有记录过
                s opsData=tempPats(episodeId)
                d opsData.Insert(opsObj) //追加
            }else {
                d opsData.Insert(opsObj)
                s tempPats(episodeId)=opsData //第一次
                d patinfo.SetAt(opsData,"opsData")
                d patInfoList.Insert(patinfo)
            }
        }
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(patInfoList),"patients")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
 
errGetOpsDataV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 闭环信息
/// w ##class(Nur.MNISV3.Service.Operation).GetOpsFlowV4("521||4")
ClassMethod GetOpsFlowV4(oeoreId)
{
    n (oeoreId)
    s $zt="errGetOpsFlowV4"
    s ^GRS("GetOpsFlowV4")=$lb(oeoreId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s opsFlow=##class(%ListOfDataTypes).%New()
    i oeoreId["，"  s OrdItemId=$p(oeoreId,"，")
    i oeoreId[","  s OrdItemId=$p(oeoreId,",")
    i $g(OrdItemId)'="" {
        s list = ##class(icare.web.TimeLineData).GetActData(OrdItemId)
        if $IsObject(list) {
            i list.%ClassName()="JsonObject" {
                s opsJson=list.Json()
                s opsObj= ##class(Nur.MNISV3.Common.JSON).Decode(opsJson)
                s opsFlow=opsObj.GetAt("ActData")
            }  
        }
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(opsFlow),"opsFlow")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetOpsFlowV4
   s Msg=$ze
   q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// CreatDate:    2018-08-28
/// Description:  查询本病区手术申请患者列表
/// Input：       wardId 病区Id
/// d ##class(%ResultSet).RunQuery("Nur.MNISV3.Service.Operation","QueryOrderList","5")
Query QueryOrderList(wardId As %String, startDate = "", startTime = "", endDate = "", endTime = "") As %Query(ROWSPEC = "opnName:%String,state:%String,applyDate:%String,applyTime:%String,opDoctor:%String,opRoom:%String,opApplyid:%String,patinfo:%String,overDate:%String,overTime:%String,anmethod,stDateTime,opaAdmDr")
{
}

ClassMethod QueryOrderListExecute(ByRef qHandle As %Binary, wardId As %String, startDate = "", startTime = "", endDate = "", endTime = "") As %Status
{
    Set repid=$I(^CacheTemp)
    If $g(ind)="" Set ind=1
    s ^LMS("QueryOrderList")=wardId
    //默认查前三天到明天
    i startDate="" s sdate=+$h-2
    e  s sdate=$zdh(startDate,3)
    i startDate="" s edate=+$h+1
    e  s edate=$zdh(endDate,3)
    s SubNode="AppDate"
    s SubNode="SDate"
    if $d(^CIS.AN.OperScheduleD)
    {
        for Date=sdate:1:edate   //Date:手术日期
        {
            set opsId=0
            for
            {
                set opsId=$order(^CIS.AN.OperScheduleI("OPDate",Date,opsId)) quit:(opsId="")  //手术日期的索引
                set operSchedule=##class(CIS.AN.OperSchedule).%OpenId(opsId)   //手术申请表
                
                s PatWardID=operSchedule.PatWardID   /// 手术申请时，患者所在的科室ID
                set EpisodeID=operSchedule.EpisodeID   /// 就诊ID  PA_Adm
                continue:EpisodeID=""
                i (PatWardID="") s PatWardID=$p(^PAADM(EpisodeID),"^",70)
                continue:wardId'=PatWardID
                /// (opname,state,applyDate,applyDate_" "_applytime,opdoctor,oproom,opapplyid,patinfo,overDate,overTime,anmethod) 
                s (opname,state,opdoctor,oproom,bedCode,overDate,overTime,anmethod,stDateTime)="",opaAdmDr=EpisodeID
                i (operSchedule.OperDate'="")&&(operSchedule.OperTime'="") s stDateTime=$zd(operSchedule.OperDate,3)_" "_$zt(operSchedule.OperTime,1)
                s OperListRowId=0
                for
                {
                    s OperListRowId=$o(^CIS.AN.OperListI("IOPS",opsId,OperListRowId)) q:OperListRowId=""  //CIS.AN.OperList 实施手术信息
                    s OPERDesc=""
                    s OperationId=$LISTGET($G(^CIS.AN.OperListD(OperListRowId)),2)  //手术rowid ORC_Operation
                    s:OperationId'="" OPERDesc=$p($g(^ORC("OPER",OperationId)),"^",2)   //手术名称
                    continue:(OPERDesc="")
                    s bodySite=$lg($g(^CIS.AN.OperListD(OperListRowId)),5)
                    i (bodySite'="") s OPERDesc=OPERDesc_bodySite
                    i (opname'="") s opname=opname_", "
                    s opname=opname_OPERDesc
                }
                if (operSchedule.Status'="")   /// 手术状态  //CT.AN.OperStatus
                {
                    set StatusID=operSchedule.Status.%Id()
                    set StatusCode=operSchedule.Status.Code
                    continue:((StatusCode="Cancel")||(StatusCode="Decline"))  ///过滤掉状态为取消和拒绝的手术 
                    set state=operSchedule.Status.Description
                }
                s applyDate=operSchedule.AppDate
                s applytime=operSchedule.AppTime
                i (applyDate'="") s applyDate=$ZD(applyDate,3)
                i (applytime'="") s applytime=$ZT(applytime,2)
                s AppUserID=operSchedule.AppUserID
                i (AppUserID'="") s opdoctor=$P($G(^SSU("SSUSR",AppUserID)),"^",2)
                s OperRoom=operSchedule.OperRoom
                i (OperRoom'="") s oproom=OperRoom.Description
                s opapplyid=opsId
                s Papmidr=$P(^PAADM(opaAdmDr),"^",1)
                s bedSub=$p($g(^PAADM(opaAdmDr)),"^",73)
                i bedSub'="" s bedCode=$p($g(^PAWARD($p(bedSub,"||",1),"BED",$p(bedSub,"||",2))),"^",1)
                e  s bedCode=""      
                s Name=$P(^PAPER(Papmidr,"ALL"),"^",1)
                s patinfo=bedCode_" "_Name
                s anaId=$o(^CIS.AN.AnaesthesiaI("IOPS",opsId,0))
                i (anaId'="") d
                .s anaObj=##class(CIS.AN.Anaesthesia).%OpenId(anaId)
                .s OperFinishDT=anaObj.OperFinishDT
                .s overDate=$p(OperFinishDT," "),overTime=$p(OperFinishDT," ",2)
                .s anmethod=anaObj.AnaMethod
                .i (anaObj.OperStartDT'="") s stDateTime=anaObj.OperStartDT
                .d anaObj.%Close()
                d operSchedule.%Close()
                s Data=$lb(opname,state,applyDate,applyDate_" "_applytime,opdoctor,oproom,opapplyid,patinfo,overDate,overTime,anmethod,stDateTime,opaAdmDr) 
                d OutputRow
            }   
        }
    } else {
        f date=sdate:1:edate
        {   
            s opaId=""
            f  s opaId=$O(^DHCANOPArrange(0,SubNode,date,opaId)) q:opaId=""  d
            .q:$d(^DHCANOPArrange(opaId))<1 
            .s opaAdmDr=$P(^DHCANOPArrange(opaId),"^",1)
            .//申请时间
            .s opAppdate=$P(^DHCANOPArrange(opaId),"^",3)         //wkz 071225 S
            .s opApptime=$P(^DHCANOPArrange(opaId),"^",5)
            .s applytime=$P(^DHCANOPArrange(opaId),"^",5)
            .i applytime'=""  s applytime=$ZT(applytime,2)
            .s SttDate=$p($g(^DHCANOPArrange(opaId)),"^",7)
            .;q:SttDate'=(+$h)
            .i opAppdate'=""  s opAppdate=$ZD(opAppdate,3)
            .i opApptime'=""  s opApptime=$ZT(opApptime,2)
            .s overDate=$p($g(^DHCANOPArrange(opaId)),"^",16)     //手术结束日期
            .s overTime=$p($g(^DHCANOPArrange(opaId)),"^",17)     //手术结束时间
            .i overDate'=""  s overDate=$ZD(overDate,3)
            .i overTime'=""  s overTime=$ZT(overTime,2)
            .//状态
            .s opaStatus=$P(^DHCANOPArrange(opaId),"^",27)
            .s opaPatStatus=$P(^DHCANOPArrange(opaId),"^",23)
            .s status=""
            .i opaStatus="A" s status="申请"
            .i (opaStatus="D")&(opaPatStatus'="I") s status="拒绝"
            .i opaStatus="R" s status="安排"
            .i opaStatus="N" s status="非预约"
            .i opaStatus="I" s status="术中"
            .i opaStatus="P" s status="恢复室"
            .i opaStatus="L" s status="术毕"
            .i opaStatus="F" s status="完成"      
            .i (opaStatus="D")&(opaPatStatus="I") s status="撤销" 
            .s Surgeon="",OpRoom="",OrdNo="",OpName=""
            .;手术间
            .s oproomdr=$P(^DHCANOPArrange(opaId),"^",20)
            .i oproomdr'="" s OpRoom=$p($g(^DHCANC("OPRoom",oproomdr)),"^",2)
            .;手术台次
            .s opordno=$P(^DHCANOPArrange(opaId),"^",26)
            . s opordnoT=opordno
            .i +opordnoT=0 s opordnoT=""
            .e  s opordnoT=opordnoT-1
            .i opordnoT>0 s OrdNo="接台"_opordno
            .i opordno=1 s OrdNo="首台"   
            .s chl=$P($P(^DHCANOPArrange(opaId),"^",2),"||",2)
            .s subchl=0 f  s subchl=$O(^OR(opaAdmDr,"ANA",chl,"OP",subchl)) q:(subchl="")  d                
            ..;手术医生
            ..s docdr=$P(^OR(opaAdmDr,"ANA",chl,"OP",subchl),"^",8)
            ..i docdr'="" d
            ...s Surgeon=$p($g(^CTPCP(+docdr,1)),"^",2)
            ..;手术名称
            ..s opdr=$P(^OR(opaAdmDr,"ANA",chl,"OP",subchl),"^",6)
            ..q:opdr=""
            ..if $D(^ORC("OPER",opdr)) d
            ...i OpName="" s OpName=$P(^ORC("OPER",opdr),"^",2)
            ...e  s OpName=$G(OpName)_"^"_$P(^ORC("OPER",opdr),"^",2)
            ..s ash=""
            ..s opaDocNote=$P(^DHCANOPArrange(opaId),"^",42) //手动填写OPA_OpDocNote（实习医生1;实习医生2...|主刀|一助|二助|三助|四助|五助...）
            ..s len=$l(opaDocNote,"|")      
            .s opname=OpName
            .s state=status
            .s applyDate=opAppdate
            .s opdoctor=Surgeon_","_$g(ash)
            .s oproom=OpRoom_" "_OrdNo  
            .i oproom="" s oproom="未排"
            .s opapplyid=opaId 
            .s Papmidr=$P(^PAADM(opaAdmDr),"^",1)
            .s ctlocdr=$P(^PAADM(opaAdmDr),"^",4)
            .s wardid=$p(^PAADM(opaAdmDr),"^",70)
            .q:wardId'=wardid
            .s bedSub=$p($g(^PAADM(opaAdmDr)),"^",73)
            .i bedSub'="" s bedCode=$p($g(^PAWARD($p(bedSub,"||",1),"BED",$p(bedSub,"||",2))),"^",1)
            .e  s bedCode=""      
            .s Name=$P(^PAPER(Papmidr,"ALL"),"^",1)
            .s patinfo=bedCode_" "_Name
            .s anmthdr=$p($g(^OR(opaAdmDr,"ANA",chl)),"^",5)
            .s anmethod=""
            .i (anmthdr'="") d
            ..s anmetNum=$l(anmthdr,"|")
            ..f i=1:1:anmetNum d
            ...s anmetId=$p(anmthdr,"|",i)
            ...q:(anmetId="")
            ...s anmetDesc=$p($g(^ORC("ANMET",anmetId)),"^",2)
            ...i (anmetDesc["-") s anmetDesc=$p(anmetDesc,"-",2)
            ...i (anmethod'="") s anmethod=anmethod_","
            ...s anmethod=anmethod_anmetDesc
            .s Data=$lb(opname,state,applyDate,applyDate_" "_applytime,opdoctor,oproom,opapplyid,patinfo,overDate,overTime,anmethod,"",opaAdmDr) 
            .d OutputRow    
        }
    }
    Set qHandle=$lb(0,repid,0)
    k TMP($zn,$j)
    Quit $$$OK
OutputRow

    Set ^CacheTemp(repid,ind)=Data
    Set ind=ind+1
    quit
}

ClassMethod QueryOrderListFetch(ByRef qHandle As %Binary, ByRef Row As %List, ByRef AtEnd As %Integer = 0) As %Status [ PlaceAfter = QueryOrderListExecute ]
{
    Set AtEnd=$LIST(qHandle,1)
    Set repid=$LIST(qHandle,2)
    Set ind=$LIST(qHandle,3)
    //
    Set ind=$o(^CacheTemp(repid,ind))
    If ind="" {             // if there are no more rows, finish fetching
        Set AtEnd=1
        Set Row=""
    }
    Else      {             // fetch row
        Set Row=^CacheTemp(repid,ind)
    }
    // Save QHandle
    s qHandle=$lb(AtEnd,repid,ind)
    Quit $$$OK
}

ClassMethod QueryOrderListClose(ByRef qHandle As %Binary) As %Status [ PlaceAfter = QueryOrderListExecute ]
{
    Set repid=$LIST(qHandle,2)
    Kill ^CacheTemp(repid)
    Quit $$$OK
}

/// 兼容老板本-获取PDA手术列表
/// w ##class(Nur.MNISV3.Service.Operation).GetOperationList("3","2024-01-12","09:36","2025-06-11","09:36")
ClassMethod GetOperationList(wardId, startDate = "", startTime = "", endDate = "", endTime = "")
{
    n (wardId,startDate,startTime,endDate,endTime)
    s $zt="errorGetOperationList"
    s ^GRS("GetOperationList")=$lb(wardId,startDate,startTime,endDate,endTime)
    s msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s operationList=##class(%ListOfDataTypes).%New()
    s operationObj=##class(%ResultSet).%New("Nur.MNISV3.Service.Operation:QueryOrderList")
    d operationObj.Execute(wardId,startDate,startTime,endDate,endTime)
    while (operationObj.Next())
    {
        s operationInfo=##class(%ArrayOfDataTypes).%New()
        s opsData=##class(%ListOfDataTypes).%New()
        s opsObj=##class(%ArrayOfDataTypes).%New()
        f len=1:1:operationObj.GetColumnCount()
        {
             s ColumnName=operationObj.GetColumnName(len)
             s Value=operationObj.GetDataByName(ColumnName)
             i ColumnName="opnName" d opsObj.SetAt(Value,"OperDesc")
             i ColumnName="opRoom" d opsObj.SetAt(Value,"RoomDesc")
             i ColumnName="stDateTime" d opsObj.SetAt(Value,"OperDate")
             i ColumnName="anmethod" d opsObj.SetAt(Value,"AnaMethodDesc")
             i ColumnName="opDoctor" d opsObj.SetAt(Value,"SurgeonDesc")
             i ColumnName="state" d opsObj.SetAt(Value,"StatusDesc")
        }
        d opsData.Insert(opsObj)
        s episodeId=operationObj.GetDataByName("opaAdmDr")
        //基本患者信息
        s operationInfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(operationInfo,episodeId)
        d operationInfo.SetAt(opsData,"opsData")
        d operationList.Insert(operationInfo)     
    }
    
    d json.SetAt($g(msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(operationList),"patients")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errorGetOperationList
    s msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(msg,"100021","-1")
}

}
